<template>
  <div>
    <el-divider>{{ $t("formgen.option.optionSet") }}</el-divider>
    <el-radio-group
      v-model="activeData.config.optionsType"
      @change="handleSetItemOpenQuery"
    >
      <el-radio-button :value="0">{{ $t("formgen.option.staticData") }}</el-radio-button>
      <el-radio-button :value="1">{{ $t("formgen.option.dynamic") }}</el-radio-button>
      <el-radio-button :value="2">{{ $t("formgen.option.dictionary") }}</el-radio-button>
      <el-radio-button :value="3">{{ $t("formgen.option.formData") }}</el-radio-button>
    </el-radio-group>

    <!-- 远程赋值配置 -->
    <div v-if="activeData.config.optionsType === 1">
      <el-input
        v-model="activeData.config.dynamicOptions.url"
        @change="handleReQueryOptionsData"
        size="default"
        placeholder="https://api.xxxx.com/xxx.json"
      >
        <template #prepend>{{ $t("formgen.option.url") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.dataPath"
        placeholder="data"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.listPath") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.valueField"
        placeholder="value"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.value") }}</template>
      </el-input>
      <el-input
        v-model="activeData.config.dynamicOptions.labelField"
        placeholder="label"
        size="small"
        @change="handleReQueryOptionsData"
      >
        <template #prepend>{{ $t("formgen.option.label") }}</template>
      </el-input>
    </div>
    <div
      v-if="activeData.config.optionsType === 0 && ['SELECT', 'MULTIPLE_SELECT'].includes(activeData.typeId)"
      class="mt10"
    >
      <draggable
        :animation="340"
        v-model="activeData.config.options"
        group="selectItem"
        handle=".option-drag"
        item-key="value"
      >
        <template #item="{ element, index }">
          <div class="select-item">
            <div class="select-line-icon option-drag">
              <el-icon>
                <ele-Operation />
              </el-icon>
            </div>
            <el-input
              v-model="element.label"
              :placeholder="$t('formgen.option.optionName')"
              size="small"
            ></el-input>
            <div
              class="close-btn select-line-icon"
              @click="activeData.config.options.splice(index, 1)"
            >
              <el-icon>
                <ele-Remove />
              </el-icon>
            </div>
          </div>
        </template>
      </draggable>
      <div style="margin-left: 20px; margin-bottom: 10px">
        <el-button
          icon="ele-CirclePlus"
          link
          type="primary"
          @click="addSelectItem"
        >
          {{ $t("formgen.option.addOption") }}
        </el-button>
        <el-button
          icon="ele-DocumentCopy"
          link
          type="primary"
          @click="openBatchEditDialogHandle"
        >
          {{ $t("formgen.option.batchAdd") }}
        </el-button>
      </div>
      <el-dialog
        :title="$t('formgen.option.batchAdd')"
        v-model="dialogVisible"
        width="50%"
      >
        <div class="desc-text">{{ $t("formgen.option.lineByOption") }}</div>
        <div>
          <el-input
            v-model="batchItemValue"
            :autosize="{ minRows: 20, maxRows: 5000 }"
            :placeholder="$t('formgen.option.batchDesc')"
            type="textarea"
          />
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">{{ $t("formI18n.all.cancel") }}</el-button>
            <el-button
              type="primary"
              @click="batchEditSelectItems"
            >
              {{ $t("formI18n.all.confirm") }}
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div v-if="activeData.config.optionsType === 2">
      <el-form-item
        :label="$t('formgen.option.dictionarySelect')"
        class="mt10"
      >
        <el-select
          v-model="activeData.config.dictOptionType"
          :placeholder="$t('formgen.option.dictionarySelect')"
          @change="handleReQueryOptionsData"
        >
          <el-option
            v-for="item in dictTypeList"
            :key="item.dictType"
            :label="item.dictName"
            :value="item.dictType"
          />
        </el-select>
      </el-form-item>
    </div>
    <div
      v-if="activeData.config.optionsType === 3"
      class="mt10 mb10"
    >
      <el-form-item
        :label="$t('formgen.option.formSelect')"
        class="mt10"
      >
        <el-select-v2
          @change="(val: string) => handleFormKeyChange(val)"
          v-model="activeData.config.linkFormKey"
          :options="allForms"
          filterable
          clearable
          :placeholder="$t('formgen.option.formSelect')"
          class="select-width"
        >
          <template #default="{ item }">
            <span style="color: var(--el-text-color-secondary); font-size: 13px">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="item.label"
                placement="right-start"
              >
                <span>{{ item.label }}</span>
              </el-tooltip>
            </span>
          </template>
        </el-select-v2>
      </el-form-item>
      <el-form-item
        :label="$t('formgen.option.itemSelect')"
        class="mt10"
      >
        <el-select-v2
          @change="handleSetItemOpenQuery"
          v-model="activeData.config.linkFormItemId"
          :options="formItemList"
          filterable
          clearable
          :placeholder="$t('formgen.option.itemSelect')"
          class="select-width"
        >
          <template #default="{ item }">
            <span style="color: var(--el-text-color-secondary); font-size: 13px">
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="item.label"
                placement="right-start"
              >
                <span>{{ item.label }}</span>
              </el-tooltip>
            </span>
          </template>
        </el-select-v2>
      </el-form-item>
    </div>
    <div class="mt20">
      <el-form-item :label="$t('formgen.option.optionRandom')">
        <el-switch v-model="activeData.config.optionRandom" />
      </el-form-item>
      <el-form-item :label="$t('formgen.option.fixedLastOption')">
        <el-switch v-model="activeData.config.lastOptionNotRandom" />
      </el-form-item>
    </div>
  </div>
</template>

<script setup lang="ts" name="ConfigItemOption">
import { defineProps, onMounted, ref } from "vue";
import { join } from "lodash-es";
import draggable from "vuedraggable";
import { DictType, optionselect } from "@/api/system/dict/type";
import { useFormOption } from "@/views/formgen/components/FormItem/hooks/useFormOptionHook";
import { FormRey, getMyHasPermissionRequest, listProjectItemRequest } from "@/api/project/form";
import { ResultData } from "@/api/types";
import { setItemOpenQuery } from "@/views/formgen/api";
import { formItemConvertData } from "@/views/formgen/utils/convert";
import { useRoute } from "vue-router";

const props = defineProps({
  activeData: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

interface Option {
  label: string;
  value: string;
}

const batchItemValue = ref("");
const dialogVisible = ref(false);
const dictTypeList = ref<DictType[]>([]);

// 全部题目
const allForms = ref<Option[]>([]);
const formItemList = ref<Option[]>([]);

onMounted(async () => {
  optionselect().then(res => {
    dictTypeList.value = res.data;
  });
  getMyHasPermissionRequest().then((res: ResultData<FormRey[]>) => {
    if (res.data) {
      allForms.value = res.data.map(item => {
        return {
          label: item.textName || "",
          value: item.formKey || ""
        };
      });
    }
  });
  if (props.activeData.config.linkFormKey) {
    handleFormKeyChange(props.activeData.config.linkFormKey, true);
  }
});

const handleFormKeyChange = (formKey: string, isInit = false) => {
  if (formKey) {
    listProjectItemRequest({ key: formKey }).then((res: any) => {
      if (res.data) {
        formItemList.value = res.data.map((item: any) => {
          return {
            label: item.textLabel,
            value: item.formItemId
          };
        });
      }
    });
  }
  if (!isInit) {
    props.activeData.config.linkFormItemId = "";
  }
  handleSetItemOpenQuery();
};

const formOption = useFormOption();

const handleReQueryOptionsData = async () => {
  const config = props.activeData.config;
  props.activeData.config.options = await formOption.getOptions(config);
};

const addSelectItem = () => {
  let max = 1;
  if (props.activeData.config.options) {
    max = Math.max(...props.activeData.config.options.map((item: Option) => item.value), 1) + 1;
  }
  props.activeData.config.options.push({
    label: "",
    type: "option",
    value: max
  });
};

const openBatchEditDialogHandle = () => {
  batchItemValue.value = join(
    props.activeData.config.options.map((item: Option) => item.label),
    "\n"
  );
  dialogVisible.value = true;
};

const batchEditSelectItems = () => {
  const arrStrs = batchItemValue.value;
  const arr = arrStrs.split("\n");
  if (arr.length > 1) {
    const options = [];
    for (let index = 0; index < arr.length; index++) {
      const element = arr[index];
      if (element) {
        options.push({
          type: "option",
          label: element,
          value: index + 1
        });
      }
    }
    props.activeData.config.options = options;
    dialogVisible.value = false;
  }
};

const route = useRoute();

const handleSetItemOpenQuery = () => {
  if (route.query.key) {
    setItemOpenQuery(formItemConvertData(props.activeData, route.query.key as string));
  }
  // 判断值是不是数组类型
  if (Array.isArray(props.activeData.config.defaultValue)) {
    props.activeData.config.defaultValue = [];
  } else {
    props.activeData.config.defaultValue = null;
  }
};
</script>

<style lang="scss" scoped>
@use "../../../assets/styles/config/options.scss" as *;
</style>
